package com.idc.resource.service;

import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import com.idc.resource.help.RedisHelp;
import com.idc.resource.model.UserInfoResDto;
import com.idc.resource.util.CacheKeyUtils;
import com.idc.resource.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 令牌服务
 * Created by Lijing on 2017/7/5.
 */
@Slf4j
@Service
public class TokenService {

    /** redis缓存服务 */
    @Autowired
    private RedisHelp redisHelp;
    /** 用户信息失效时间 */
    private static final Long user_info_lose = 60*60L;
    /** 登录令牌失效时间 */
    private static final Long token_lose_time = 30*60L;


    /**
     * 登录令牌处理
     * @param userInfo 登录用户信息
     */
    public void loginIn(UserInfoResDto userInfo){
        String token = TokenUtil.createToken();
        userInfo.setToken(token);
        String loginKey = CacheKeyUtils.buildLoginKey(token);
        String loginLoseKey = CacheKeyUtils.buildLoginLoseKey(token);
        redisHelp.insertObject(loginKey,userInfo,user_info_lose);
        redisHelp.insertObject(loginLoseKey,"令牌有效",token_lose_time);
    }

    /**
     * 令牌销毁
     * @param token 登录令牌
     */
    public void destroyToken(String token){
        String loginKey = CacheKeyUtils.buildLoginKey(token);
        String loginLoseKey = CacheKeyUtils.buildLoginLoseKey(token);
        redisHelp.deleteObject(loginKey);
        redisHelp.deleteObject(loginLoseKey);
    }

    /**
     * 获取登录用户信息
     * @param token 令牌
     * @return 用户信息
     */
    public UserInfoResDto getLoginUser(String token){
        String loginKey = CacheKeyUtils.buildLoginKey(token);
        String loginLoseKey = CacheKeyUtils.buildLoginLoseKey(token);
        String lose = redisHelp.queryObjectByKey(loginLoseKey);
        if(StringUtils.isBlank(lose)){
            log.error("用户登录已超时");
            throw new IdcServiceException(ErrorCodeEnum.LOGIN_LOSE.getCode(),ErrorCodeEnum.LOGIN_LOSE.getDesc());
        }
        UserInfoResDto userInfo = redisHelp.queryObjectByKey(loginKey,UserInfoResDto.class);
        if(userInfo==null){
            log.error("缓存中未查询到用户信息，登录已超时");
            throw new IdcServiceException(ErrorCodeEnum.LOGIN_LOSE.getCode(),ErrorCodeEnum.LOGIN_LOSE.getDesc());
        }
        return userInfo;
    }

    /**
     * 刷新登录令牌有效时间
     * @param token 登录令牌
     * @return 刷新结果
     */
    public boolean refreshToken(String token){
        String loginKey = CacheKeyUtils.buildLoginKey(token);
        String loginLoseKey = CacheKeyUtils.buildLoginLoseKey(token);
        if(redisHelp.expire(loginLoseKey,token_lose_time)){
            return redisHelp.expire(loginKey,user_info_lose);
        }
        return false;
    }

}
